import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 参数1：仓库的名字
 */
export const useCartStore = defineStore(
  'cart',
  () => {
    const cartList = ref([])

    // 定义加入购物车的方法
    const addToCart = goods => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.number += goods.number
      } else {
        cartList.value.push(goods)
      }
    }

    // 更改商品的选中状态
    /**
     * goods 中 它是有两个属性 {proid:'',state: true/false}
     */
    const updateGoodsState = goods => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.state = goods.state
      }
    }

    // 更改商品的数量
    /**
     * goods 中 它是有两个属性 {proid:'',state: true/false}
     */
    const updateGoodsNumber = goods => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.number = goods.number
      }
    }

    // 根据商品id去删除对应的商品
    const deleteGoodsById = proid => {
      const index = cartList.value.findIndex(item => item.proid === proid)
      if (index > -1) {
        cartList.value.splice(index, 1)
      }
    }

    // 计算出购物车中商品的总数
    const total = computed(() =>
      cartList.value.reduce((total, item) => total + item.number, 0)
    )

    // 是否全部选中
    const isAllSelect = computed(() => cartList.value.every(item => item.state))

    // 选中的总金额
    const totalAmount = computed(() =>
      cartList.value
        .filter(item => item.state)
        .reduce((total, item) => total + item.number * item.price, 0)
    )

    // 全选 & 反选
    const selectAllOrNot = state => {
      cartList.value.forEach(item => (item.state = state))
    }

    return {
      cartList,
      addToCart,
      updateGoodsState,
      updateGoodsNumber,
      deleteGoodsById,
      isAllSelect,
      selectAllOrNot,
      totalAmount,
      total
    }
  },
  {
    persist: true
  }
)
